In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
import cv2
# Visualizations will be shown in the notebook.
%matplotlib inline
# TODO: Fill this in based on where you saved the training and testing data
# Load Trining Data and safe it
training_file = './Training_Set/train.p'
validation_file= './Training_Set/valid.p'
testing_file = './Training_Set/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
print(len(X_train), X_train.shape)
print(len(X_valid), X_valid.shape)
print(len(X_test), X_test.shape)
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0]
# TODO: Number of testing examples.
n_test = X_test.shape[0]
# TODO: Number of validation examples.
n_valid = X_valid.shape[0]
# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape[1:3]
# TODO: How many unique classes/labels there are in the dataset.
class_names = pd.read_csv('signnames.csv', index_col=0)
n_classes = len(class_names)
# Print numbers of Training data, image shape and count of classes in data set
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Number of valid examples =", n_valid)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
sign_names = pd.read_csv("signnames.csv")
sign_names.set_index("ClassId")
sign_names.head(n=3)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
n_columns = 7
f, ax = plt.subplots(n_classes, n_columns, figsize=(20, 120))
for c in range(n_classes):
sample_indexes = np.where(y_train==c)[0]
sample_list = np.random.choice(sample_indexes, size=n_columns, replace=False)
ax[c, 1].set_title('%s, number of samples: %d' % (class_names.loc[c]['SignName'], len(sample_indexes)))
for idx, sample in enumerate(sample_list):
ax[c, idx].imshow(X_train[sample, :, :, :])
ax[c, idx].set_axis_off()
# sample stats
plt.figure(figsize=(20, 5))
ax = plt.hist(y_train, bins=np.arange(0, n_classes))
plt.xlabel("Sample Count", fontdict=None, labelpad=None)
plt.ylabel("Number of Instances", fontdict=None, labelpad=None)
labels = y_train
c = Counter(labels)
print(c.items())
signal = []
count = []
for v in c.values():
count.append([v])
for w in c.keys():
signal.append([w])
plt.plot(signal,count, 'o')
plt.show()
# Visualizations will be shown in the notebook.
def maxfreq(y_train, n_class):
counts = []
for i in range(n_class):
counts.append(np.sum(y_train == i))
return max(counts)
def minfreq(y_train, n_class):
counts = []
for i in range(n_class):
counts.append(np.sum(y_train == i))
return min(counts)
def sumfreq(y_train, n_class):
counts = []
for i in range(n_class):
counts.append(np.sum(y_train == i))
return sum(counts)
maxf = maxfreq(y_train, 43)
minf = minfreq(y_train, 43)
gap = maxf - minf
## UPPERLIMIT = gap
UPPERLIMIT = maxf
sumfreq = sumfreq(y_train, 43)
print('max freq = ', maxf)
print('min freq = ', minf)
print ('upperlimit = ', UPPERLIMIT)
print('sum of all frequencies = ', sumfreq)
training_mean = (sumfreq/n_classes) ## --> get the mean count
print('mean = ', training_mean)
maxperturb = UPPERLIMIT // minf
print('max perturbations required = ', maxperturb)
#This plot does the same as the plot before but the visualization is easier
def display_data(y_train, n_class):
counts = []
for i in range(n_class):
counts.append(np.sum(y_train == i))
plt.bar(range(43),counts)
plt.xlabel("Sample Count", fontdict=None, labelpad=None)
plt.ylabel("Number of Instances", fontdict=None, labelpad=None)
print('The data shown before augmentation...')
display_data(y_train, 43)
## Note: allspace = whitespace + bar_space
bar_space = sumfreq
allspace = maxf * n_classes
whitespace = allspace - bar_space
print('allspace = ', allspace)
print('bar_space = ', bar_space)
print('whitespace = ', whitespace)
### Oversampling to increase the underrepresented class labels.
# Use RandomOverSampler to create a consistant data set
from imblearn.over_sampling import RandomOverSampler
dataset_size = len(X_train)
X_train = X_train.reshape(dataset_size,-2)
print(X_train.shape)
print(X_train[0].shape)
ros = RandomOverSampler()
X_resampled,y_resampled = ros.fit_sample(X_train,y_train)
print(X_resampled.shape)
print(y_resampled.shape)
dataset_size = len(X_train)
X_train = np.reshape(X_resampled,(86430,32,32,3))
y_train = y_resampled
print(X_train.shape)
print(X_train[0].shape)
# Display the oversampled datapoints
print('The data shown after over sampling...')
display_data(y_train, 43)
# Just plot some images to check
plt.subplot(221)
plt.imshow(X_train[50000])
plt.subplot(222)
plt.imshow(X_train[60000])
plt.subplot(223)
plt.imshow(X_train[70000])
plt.subplot(224)
plt.imshow(X_train[80000])
# The equilize function prepares the image with a Color filter for further use
def equalize_hist(img):
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
# equalize the histogram of the Y channel only
img_yuv[:,:,0] = cv2.equalizeHist(np.array(img_yuv[:,:,0]).astype(np.uint8))
#apply contrast limited adaptive histogram equalization
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
img_yuv[:,:,0] = clahe.apply(img_yuv[:,:,0])
img_yuv = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
return img_yuv
def equalize_data(data):
print("Equalizing...")
for i in range(len(data)):
data[i] = equalize_hist(np.array(data[i]))
return data
# All three sets of data are prepared with the equlize function to feed into the network
img_bef_hist = np.copy(X_test[1])
#histogram equalization on all data
X_train = equalize_data(X_train)
X_valid = equalize_data(X_valid)
X_test = equalize_data(X_test)
img_after_hist = X_test[1]
f, axarr = plt.subplots(1, 2, figsize=(5,5))
plt.figure()
f.subplots_adjust(hspace = .4, wspace=.001)
subtitle1 = "Before Equalization"
axarr[0].set_title(subtitle1, fontsize=10)
axarr[0].set_aspect(aspect=1, adjustable='box')
axarr[0].imshow(img_bef_hist)
subtitle2 = "After Equalization"
axarr[1].set_title(subtitle2, fontsize=10)
axarr[1].set_aspect(aspect=1, adjustable='box')
axarr[1].imshow(np.round(img_after_hist).astype(np.uint8))
plt.savefig('hist_compare.png', bbox_inches='tight')
#sort training set after data equlization for visualization
sorted_indices = np.argsort(y_test)
y_test = y_test[sorted_indices]
X_test = X_test[sorted_indices]
u, indices, freq = np.unique(y_test, return_index=True, return_counts=True)
sorted_indices = np.argsort(u)
u = u[sorted_indices]
indices = indices[sorted_indices]
freq = freq[sorted_indices]
# This block just prints all the data equalized to check if it worked
n_columns = 7
f, ax = plt.subplots(n_classes, n_columns, figsize=(20, 120))
for c in range(n_classes):
sample_indexes = np.where(y_train==c)[0]
sample_list = np.random.choice(sample_indexes, size=n_columns, replace=False)
ax[c, 1].set_title('%s, number of samples: %d' % (class_names.loc[c]['SignName'], len(sample_indexes)))
for idx, sample in enumerate(sample_list):
ax[c, idx].imshow(X_train[sample, :, :, :])
ax[c, idx].set_axis_off()
# sample stats
plt.figure(figsize=(20, 5))
ax = plt.hist(y_train, bins=np.arange(0, n_classes))
labels = y_train
c = Counter(labels)
print(c.items())
# This shows the destributin of the training, validation and testing set for the classes. As seen, the training class is oversampled
bins = range(n_classes)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(20, 10))
ax0.hist(y_train, bins, histtype='stepfilled', facecolor='g')
ax0.set_title('Training Set Distribution')
# Create a histogram by providing the bin edges (unequally spaced).
ax1.hist(y_valid, bins, histtype='stepfilled', facecolor='y')
ax1.set_title('Validation Set Distribution')
# Create a histogram by providing the bin edges (unequally spaced).
ax2.hist(y_test, bins, histtype='stepfilled', facecolor='r')
ax2.set_title('Test Set Distribution')
ax0.set_xlabel('Sample Count')
ax0.set_ylabel('Number of Instances')
ax1.set_xlabel('Sample Count')
ax1.set_ylabel('Number of Instances')
ax2.set_xlabel('Sample Count')
ax2.set_ylabel('Number of Instances')
fig.tight_layout()
plt.show()
plt.savefig('data_explore.png', bbox_inches='tight')
plt.close('all')
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train)
#normalizing data
X_train = ( X_train - np.mean(X_train) ) / np.std(X_train)
X_valid = ( X_valid - np.mean(X_valid) ) / np.std(X_valid)
X_test = ( X_test - np.mean(X_test) ) / np.std(X_test)
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import tensorflow as tf
EPOCHS = 50
BATCH_SIZE = 256
from tensorflow.contrib.layers import flatten
x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, 43)
### Define your architecture here.
### Feel free to use as many code cells as needed.
mu = 0
sigma = 0.1
factor = 3
def LeNet(x):
# SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.
conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma))
conv1_b = tf.Variable(tf.zeros(6))
conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID')
conv1 = tf.nn.bias_add(conv1, conv1_b)
# SOLUTION: Activation.
conv1 = tf.nn.relu(conv1)
# SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
conv2_b = tf.Variable(tf.zeros(16))
conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID')
conv2 = tf.nn.bias_add(conv2, conv2_b)
# SOLUTION: Activation.
actv2 = tf.nn.relu(conv2)
# SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
conv2 = tf.nn.max_pool(actv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Flatten. Input = 5x5x16. Output = 400.
fc0 = flatten(conv2)
# SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
fc1_b = tf.Variable(tf.zeros(120))
fc1 = tf.add(tf.matmul(fc0, fc1_W), fc1_b)
# SOLUTION: Activation.
fc1 = tf.nn.relu(fc1)
# SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
fc2_b = tf.Variable(tf.zeros(84))
fc2 = tf.add(tf.matmul(fc1, fc2_W), fc2_b)
# SOLUTION: Activation.
fc2 = tf.nn.relu(fc2)
# SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.
fc3_W = tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev = sigma))
fc3_b = tf.Variable(tf.zeros(43))
lenet = tf.add(tf.matmul(fc2, fc3_W), fc3_b)
return lenet
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
def print_stats(session, feature_batch, label_batch, cost, accuracy):
"""
Print information about loss and validation accuracy
: session: Current TensorFlow session
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
: cost: TensorFlow cost function
: accuracy: TensorFlow accuracy function
"""
loss = session.run(cost, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.0})
validation_accuracy = sess.run(accuracy, feed_dict={
x: X_valid,
y: y_valid,
keep_prob: 1.0
})
training_accuracy = sess.run(accuracy, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.0})
print('Loss: {:>10.4f} Validation Accuracy: {:.6f} Training Accuracy: {}'.format(loss,
validation_accuracy,
training_accuracy))
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle
# y = tf.placeholder(tf.int32, (None))
# one_hot_y = tf.one_hot(y, n_classes)
rate = 0.001
logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
training_loss_history = []
validation_loss_history = []
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset + BATCH_SIZE], y_data[offset:offset + BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print('Training...')
for i in range(EPOCHS):
X_train_0, y_train_0 = shuffle(X_train, y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train_0[offset:end], y_train_0[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
train_loss = sess.run(loss_operation, feed_dict={x:X_train, y:y_train})
valid_loss = sess.run(loss_operation, feed_dict={x:X_valid, y:y_valid})
training_loss_history.append(train_loss)
validation_loss_history.append(valid_loss)
validation_accuracy = evaluate(X_valid, y_valid)
training_accuracy = evaluate(X_train, y_train)
print("EPOCH {} ...".format(i+1))
print('EPOCH %3d, validation accuracy %.3f' % (i + 1, validation_accuracy))
if validation_accuracy > 0.99:
break;
saver.save(sess, './lenet')
print("Model saved")
loss_plot = plt.subplot(2,1,1)
loss_plot.set_title('Loss')
loss_plot.plot(training_loss_history, 'r', label='Training Loss')
loss_plot.plot(validation_loss_history, 'b', label='Validation Loss')
loss_plot.set_xlim([0, EPOCHS])
loss_plot.legend(loc=4)
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, './lenet')
# evaluate on training set
training_accuracy = evaluate(X_train, y_train)
print('Model accuracy on training set = %.3f' % training_accuracy)
print()
# evaluate on test set
valid_accuracy = evaluate(X_valid, y_valid)
print('Model accuracy on validation set = %.3f' % valid_accuracy)
print()
test_accuracy = evaluate(X_test, y_test)
print('Model accuracy on test set = %.3f' % test_accuracy)
print()
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
# Import the image set and set the labes.
import cv2
import os
test_table = pd.read_csv('images/gt.csv')
n_test_samples = len(test_table)
X_test_2 = np.zeros((n_test_samples, 32, 32, 3), dtype=np.uint8)
y_test_2 = test_table['ClassId'].values.astype(np.uint8)
f, ax = plt.subplots(n_test_samples, 1, figsize=(20, 120))
for idx, row in test_table.iterrows():
img_original = cv2.cvtColor(cv2.imread(os.path.join('images', row['File']), cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)
ax[idx].imshow(img_original)
ax[idx].set_axis_off()
ax[idx].set_title(class_names.loc[row['ClassId']]['SignName'])
img_resized = cv2.resize(img_original, (32, 32))
X_test_2[idx, :, :, :] = img_resized
print(y_test_2)
# Process the imported images and normalize the images for prediction function
X_train_new_p = equalize_data(X_test_2)
X_train_new_p = (X_train_new_p - np.mean(X_train_new_p) ) / np.std(X_train_new_p)
# This is the prediction function. It uses the given images and predicts fromthe lenet the image
predictions = tf.argmax(logits, 1)
def predict_on_custom_data(X_data):
sess = tf.get_default_session()
pred = sess.run(predictions, feed_dict={x:X_data})
return pred
# The answer to the prediction is given from the trained model
with tf.Session() as sess:
saver.restore(sess, './lenet')
predictions = predict_on_custom_data(X_train_new_p)
print(predictions)
for idx, pred, actual in zip(range(len(predictions)), predictions, y_test_2):
if pred==actual:
print('%s: correctly identified "%s"' % (test_table.loc[idx]['File'], class_names.loc[pred]['SignName']))
else:
print('%s: ERROR detected "%s", actual "%s"' % (test_table.loc[idx]['File'], class_names.loc[pred]['SignName'], class_names.loc[actual]['SignName']))
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, './lenet')
# evaluate on test set
test_2_accuracy = evaluate(X_train_new_p, y_test_2)
print('Model accuracy on a custom test set = %.3f' % test_2_accuracy)
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
from pylab import rcParams
top_5 = tf.nn.top_k(tf.nn.softmax(logits), k=5)
rcParams['figure.figsize'] = 25, 30
f, axarr = plt.subplots(5, 2)
f.subplots_adjust(bottom=0.00)
top_k = 5
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, './lenet')
# evaluate on test set
test_2_top_5 = sess.run(top_5, feed_dict={x: X_train_new_p})
# print out
for idx in range(len(test_2_top_5.values)):
print('%s' % class_names.loc[y_test_2[idx]]['SignName'])
for sample in range(len(test_2_top_5.values[idx])):
print(' %.5f %s' % (test_2_top_5.values[idx, sample], class_names.loc[test_2_top_5.indices[idx, sample]]['SignName']))
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it maybe having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
input_img = np.zeros((1, 32, 32, 3), dtype=np.float32)
input_img[0, :, :, :] = X_test_2[3]
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, './lenet')
outputFeatureMap(input_img, actv2)
Discuss how you used the visual output of your trained network's feature maps to show that it had learned to look for interesting characteristics in traffic sign images
Answer: From the feature maps it can be seen that the trained network was indeed able to learn some features of a Yield sign. Some of the feature maps seem to be noisy though (not like on NVIDIA pics).
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.